package com.dingreading.cloud.admin.controller;

import com.dingreading.cloud.admin.entity.TimeTasks;
import com.dingreading.cloud.admin.service.TimeTasksService;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.DateUtil;
import com.dingreading.cloud.common.util.DescribeException;
import com.dingreading.cloud.common.util.PageBeanDto;
import com.dingreading.cloud.common.util.PageUtil;
import com.mybatisflex.core.paginate.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/timeTask")
@Api(tags = "总部-服务到期提醒")
public class TimeTaskController {

    @Resource
    private TimeTasksService timeTaskService;


    @ApiOperation(value = "分页列表")
    @PostMapping(value = "/pageList", produces = "application/json; charset=UTF-8")
    public R<Object> pageList(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "公司名/分类名/描述名") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam(value = "是否禁用 1.启用 0.禁用") @RequestParam(value = "enabled", required = false) Integer enabled
    ) {
        Page<TimeTasks> page = this.timeTaskService.pageList(pageUtil, keyword, enabled);

        PageBeanDto data = new PageBeanDto();
        data.setTotal(page.getTotalRow());
        data.setList(page.getRecords());
        return R.ok(data);
    }

    @Transactional(rollbackFor = DescribeException.class)
    @ApiOperation(value = "新增/修改")
    @PostMapping(value = "/newBean", produces = "application/json; charset=UTF-8")
    public R<Object> newBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id", required = false) Long id,
            @ApiParam(value = "公司名称") @RequestParam(value = "corpName") String corpName,
            @ApiParam(value = "分类名称") @RequestParam(value = "typeName") String typeName,
            @ApiParam(value = "服务名称") @RequestParam(value = "intro") String intro,
            @ApiParam(value = "说明") @RequestParam(value = "explains", required = false) String explains,
            @ApiParam(value = "到期时间 yyyy-MM-dd 23:59:59") @RequestParam(value = "expireTime") String expireTime
    ) throws Exception {
        TimeTasks data = null;
        if (id == null || id <= 0) {
            // 新增
            data = new TimeTasks();
            data.setEnabled(1);
        } else {
            //修改
            data = timeTaskService.getById(id);
            if (data == null) return R.fail("获取失败");
        }
        if (StringUtils.isNotBlank(corpName))
            data.setCorpName(corpName);
        if (StringUtils.isNotBlank(typeName))
            data.setTypeName(typeName);
        if (StringUtils.isNotBlank(intro))
            data.setIntro(intro);
        if (StringUtils.isNotBlank(explains))
            data.setExplains(explains);
        if (StringUtils.isNotBlank(expireTime))
            data.setExpireTime(DateUtil.parseDateFromStr(expireTime));
        timeTaskService.saveOrUpdate(data);
        return R.ok();
    }


    @ApiOperation(value = "更新启用状态")
    @PostMapping(value = "/updateEnabled", produces = "application/json; charset=UTF-8")
    public R<Object> updateEnabled(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id,
            @ApiParam(value = "状态 0.禁用 1.启用") @RequestParam(value = "enabled") Integer enabled
    ) {
        boolean l = timeTaskService.updateEnabled(id, enabled);
        if (!l) return R.fail("更新失败");
        return R.ok();
    }


    @ApiOperation(value = "获取详情")
    @PostMapping(value = "/getBean", produces = "application/json; charset=UTF-8")
    public R<Object> getBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id
    ) {
        TimeTasks data = timeTaskService.getById(id);
        if (data == null) return R.fail("获取失败");

        return R.ok(data);
    }

    @ApiOperation(value = "获取10天内即将到期的服务")
    @PostMapping(value = "/ExpireTask", produces = "application/json; charset=UTF-8")
    public R<Object> getExpireTask(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "即将到期的天数") @RequestParam(value = "day") int day
    ) {
        List<TimeTasks> tasks = timeTaskService.getExpireTask(day);
        return R.ok(tasks);
    }

    @Deprecated
    @ApiOperation(value = "获取10天内即将到期的服务，发送短信")
    @PostMapping(value = "/sendExpireTask", produces = "application/json; charset=UTF-8")
    public R<Object> sendExpireTask(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "即将到期的天数") @RequestParam(value = "day") int day
    ) {
        String phones = "18158855766";
        List<TimeTasks> tasks = timeTaskService.getExpireTask(day);
        if (CollectionUtils.isNotEmpty(tasks)) {
            StringBuilder content = new StringBuilder();
            content.append("【服务到期提醒】,");
            LinkedHashMap<String, List<TimeTasks>> map = tasks.stream().collect(Collectors.groupingBy(TimeTasks::getCorpName,
                    LinkedHashMap::new, Collectors.toList()));
            for (Map.Entry<String, List<TimeTasks>> entry : map.entrySet()) {
                String key = entry.getKey();
                List<TimeTasks> value = entry.getValue();

                content.append(key).append("[");
                if (CollectionUtils.isNotEmpty(value)) {
                    LinkedHashMap<String, List<TimeTasks>> typeMap = value.stream().collect(Collectors.groupingBy(TimeTasks::getTypeName,
                            LinkedHashMap::new, Collectors.toList()));
                    for (Map.Entry<String, List<TimeTasks>> typeEntry : typeMap.entrySet()) {
                        String typeKey = typeEntry.getKey();
                        List<TimeTasks> typeValue = typeEntry.getValue();
                        content.append(typeKey).append(":");
                        for (int i = 0; i < typeValue.size(); i++) {
                            TimeTasks task = typeValue.get(i);
                            if (i != typeValue.size() - 1) {
                                content.append(task.getIntro()).append("(")
                                        .append(DateUtil.getDefaultTime2DateStr(task.getExpireTime())).append(")").append(",");
                            } else {
                                content.append(task.getIntro()).append("(")
                                        .append(DateUtil.getDefaultTime2DateStr(task.getExpireTime())).append(")").append(";");
                            }
                        }
                    }
                }
                content.append("]");
            }

            System.out.println("sb = " + content);
            System.out.println("phones = " + phones);
        }
        return R.ok();
    }
}
